import socketio

# 实例化
sio = socketio.Client()


# 默认连接时执行
# @sio.event不适合自定义事件，只适合connect、disconnect;因为不能写namespace
@sio.event
def connect():
    sio.emit('connect', {'foo': 'bar'})
    print('connection established')


# 默认断开时执行
@sio.event
def disconnect():
    print('disconnected from server')


# 连接
sio.connect('http://127.0.0.1:8000', namespaces=['/channel_A'])

# 测试：Emitting Events
sio.emit('messages', {'foo': 'bar'}, namespace='/channel_A')


# 类似：阻塞按钮：如果执行，则下面监听使事件custom_messages、myEmail则失效
# sio.wait()

# 测试：修饰器
# @sio.event不适合自定义事件，只适合connect;因为不能写namespace
@sio.on('custom_messages', namespace='/channel_A')
def custom_messages(data):
    print('/////')
    print(str(data))


# 类似：阻塞按钮：如果执行，则下面监听使事件myEmail则失效
# sio.wait()

# 监听事件
@sio.on('myEmail', namespace='/channel_A')
def myEmail(data):
    print('myEmail received with ', data)
    # 发送事件sio.emit(对方事件名,data)
    sio.emit('response', {'response': 'my response'}, namespace='/channel_A')

# 类似：阻塞按钮
# sio.wait()
